var FormartUtils = require('FormartUtils');
var LogUtils = require("LogUtils");
var video_1 = null;
var video_1_id = "117372369179704_122337102016564";   //新添加
var video_3 = null;
var video_3_id = "117372369179704_122114078705533";  //新添加
var worldRank = "wordrank";   //leaderboard_test  wordrank
var query = require('query_player')();
var isShow = false;
function FaceBookUtils (){
    // this.m_preloadedRewardedVideo = null;
    this.m_isLoadingBigButterfly = false;
    this.m_canShowDoubelCoinAd = false; 
    this.m_canShowGetDiamondAd = false; 
    this.m_canShowGetRandomPlayerAd = false; 
    // this.m_canShowDoubelCoinAd = false; 
    //邀请facebook好友
    this.inviteFaceBookFriend = function(){
        var self = this;
        if(1) return;
        //邀请
        if (typeof FBInstant === 'undefined') return;
        FBInstant.context.chooseAsync()
        .then(function () {
            // console.info("呼出好友列表成功");
            self.FBEventStatis("Invite-Friend-UI")
            var pathName = window.location.pathname.substring(1);
            var str = "";
            if (pathName.indexOf("index.html") != -1) {
                var index = pathName.indexOf("index.html");
                str = pathName.substring(0, index);
            }
            var url = "/" + str + "shareres/shareimg_1.png";
            FormartUtils.convertImgToBase64(url, function (base64Img) {
                //转化后的base64
                // console.log(base64Img);
                // console.info("生成图片成功");
                FBInstant.updateAsync({
                    action: 'CUSTOM',
                    cta: 'Join The Fight',
                    image: base64Img,
                    text: {
                        default: 'Hi!Play Lightning Ball with me!',
                        localizations: {
                            en_US: 'Hi,Play Lightning Ball with me!',
                        }
                    },
                    template: 'VILLAGE_INVASION',
                    data: { myReplayData: '...' },
                    strategy: 'IMMEDIATE',
                    notification: 'NO_PUSH',
                }).then(function () {
                    // console.info("updateAsync");
                    // closes the game after the update is posted.
                });
            });
        }).catch(function (e) {
            // console.info("呼出好友列表异常  ", e);
        });
    };
    //分享游戏
    this.shareForFaceBook = function(bf){
        if (typeof FBInstant === 'undefined') return;
        var pathName = window.location.pathname.substring(1);
        var str = "";
        if (pathName.indexOf("index.html") != -1) {
            var index = pathName.indexOf("index.html");
            str = pathName.substring(0, index);
        }
        // console.log("str",str)
        var url = "/" + str + "shareres/shareimg_1.png";
        FormartUtils.convertImgToBase64(url, function(base64Img){
            //转化后的base64
            console.log(base64Img);
            FBInstant.shareAsync({
                intent: 'SHARE', 
                image: base64Img,
                text: 'This is a wonderful instant game!Come and join us!',
                data: {},
            }).then(function() {
                // console.log("分享测试？？？？")
                // continue with the game.
                if(bf) bf();
                var buildLayer = cc.find("Canvas/buildLayer").getComponent("BuildLayer");
                buildLayer.showSharedGetDiamondLayer();
            });
        });
    };
    //设置排行榜的数据  //可以往里面传参数
    this.setRankInfoForFaceBook = function(score){ 
        LogUtils.log("FaceBookUtils--->setRankInfoForFaceBook--->uploading Score ！！！",score)
        if (typeof FBInstant === 'undefined') return;
        score = (score).toFixed(0)
        score = Number(score)
        // console.log("给facebook上传自己的分数  排行榜使用",score)
        FBInstant.getLeaderboardAsync(worldRank)    //通过名字 回去排行榜
        .then(function(leaderboard) {
            // console.log("leaderboard.name",leaderboard.getName());
            return leaderboard.setScoreAsync(score);
        })
        .then(() => LogUtils.log('Score saved'))
        .catch(function(error) {
            // console.log("error",error)
        });
    };
    //获取玩家自己的排行榜信息
    this.getMySelfRankInfoForFaceBook = function(backFun){
        if (typeof FBInstant === 'undefined') return;
        FBInstant.getLeaderboardAsync(worldRank)
        // FBInstant.getLeaderboardAsync("wordrank")
        .then(leaderboard => leaderboard.getPlayerEntryAsync())
        .then(entry => {
            LogUtils.log("FaceBookUtils--->getMySelfRankInfoForFaceBook--->entry",entry)
            if(entry && entry.getRank){
                var myIndex = entry.getRank();
                LogUtils.log("FaceBookUtils--->getMySelfRankInfoForFaceBook--->myIndex",myIndex)
                if(backFun){
                    backFun(myIndex)
                }
            }else{
                LogUtils.log("entry.getRank error！！！")
            }
            // console.log("entry",entry)
            // console.log("entry.length",entry.length)
            // console.log(" entry.getRank()",entry.getRank() )
            // console.log(" entry.getPlayer().getName() ",entry.getPlayer().getName())
            // console.log(" entry.getScore()",entry.getScore())
            // for (let i = 0; i < entry.length; i++) {
                // console.log("entry[i]",entry[i])
                // console.log(
                //     entry[i].getRank() + '. ' +
                //     entry[i].getPlayer().getName() + ': ' +
                //     entry[i].getScore()
                // );
            // }
        }).catch(error => console.error(error));
    };
    //获取全部的排行榜信息
    this.getAllRankInfoForFaceBook = function(backFun){
        if (typeof FBInstant === 'undefined') return;
        FBInstant.getLeaderboardAsync(worldRank)
        .then(leaderboard => leaderboard.getEntriesAsync(10, 0))
        .then(entries => {
            console.log("entries",entries)
            // console.log("entries.length",entries.length)
            if(backFun){
                backFun(entries)
            }
            // for (var i = 0; i < entries.length; i++) {
            //     console.log(" entries.getRank()",entries[i].getRank() )
            //     console.log(" entries.getPlayer().getName() ",entries[i].getPlayer().getName())
            //     console.log(" entries.getPlayer().getPhoto() ",entries[i].getPlayer().getPhoto())
            //     console.log(" entries.getScore()",entries[i].getScore())
            // }
        }).catch(error => console.error(error));
    };
    /**
     * ---------------------------------双倍金币
     */
    //加载双倍金币视频
    this.preloadAd_doubelCoin = function(bf){
        var self = this;
        if (typeof FBInstant === 'undefined'){
            // cc.find("dialogLayer").getComponent("DialogLayer").show("preloadAd_doubelCoin isLocal")
            // if(bf) bf(false);
            return;
        }
        var supportedAPIs = FBInstant.getSupportedAPIs();
        if (supportedAPIs.includes('getRewardedVideoAsync')){
            FBInstant.getRewardedVideoAsync(
                video_1_id, // Your Ad Placement Id
            ).then(function(rewarded) {
                // Load the Ad asynchronously
                cc.find("dialogLayer").getComponent("DialogLayer").show("preloadAd_doubelCoin Load the Ad asynchronously")
                video_1 = rewarded;
                return video_1.loadAsync();
            }).then(function() {
                cc.find("dialogLayer").getComponent("DialogLayer").show("preloadAd_doubelCoin Rewarded video is Loaded")
                if(bf) bf(true);
            }).catch(function(err){
                cc.find("dialogLayer").getComponent("DialogLayer").show("preloadAd_doubelCoin Rewarded video failed to preload:" + err.message)
                if(bf) bf(false);
            });
        }
    };
    //播放双倍金币广告
    this.playAd_doubelCoin = function(bf){
        var self = this;
        if (typeof FBInstant === 'undefined'){
            // if(bf) bf();
            return ;
        };
        self.FBEventStatis("Double-Coins-Ads-Play")
        video_1.showAsync()
        .then(function() {
            cc.find("dialogLayer").getComponent("DialogLayer").show("playAd_doubelCoin Perform post-ad success operation")
            if(bf) bf();
        }).catch(function(e) {
            self.FBEventStatis("Double-Coins-PlayAdisError");
           cc.find("dialogLayer").getComponent("DialogLayer").show("playAd_doubelCoin error"+e.message)
        });
    };
    /**
     * ---------------------------------大蝴蝶相关的
     */
     //加载大蝴蝶的视频广告
    this.preloadAd_getBigButterflyReward = function(bf){
        var self = this;
        if (typeof FBInstant === 'undefined'){
            // cc.find("dialogLayer").getComponent("DialogLayer").show("preloadAd_getBigButterflyReward is Local");
            // if(bf) bf();
            return;
        }
        FBInstant.getRewardedVideoAsync(
            video_3_id, // Your Ad Placement Id
            ).then(function(rewarded) {
                // Load the Ad asynchronously
                self.m_isLoadingBigButterfly = true;
                self.FBEventStatis("Start-Preload-BigButterflyAd");
                cc.find("dialogLayer").getComponent("DialogLayer").show("getBigButterflyReward Load the Ad asynchronously");
                video_3 = rewarded;
                return video_3.loadAsync();
            }).then(function() {
                if(bf) bf();
                cc.find("dialogLayer").getComponent("DialogLayer").show("getBigButterflyReward Rewarded video preloaded");
                // self.m_canShowGetButterflyRewardAd = true;
                self.m_isLoadingBigButterfly = false;
                self.FBEventStatis("Preload-BigButterflyAd-Succes");
            }).catch(function(err){
                cc.find("dialogLayer").getComponent("DialogLayer").show("getBigButterflyReward err" + err.message);
                self.m_isLoadingBigButterfly = false;
                self.FBEventStatis("Preload-BigButterflyAd-Error");
                // if(bf) bf();
                // self.m_canShowGetButterflyRewardAd = false;
        });
    };
     //播放大蝴蝶的广告
    this.playAd_getBigButterflyReward = function(bf){
        var self = this;
        if (typeof FBInstant === 'undefined') {
            // cc.find("dialogLayer").getComponent("DialogLayer").show("playAd_getBigButterflyReward is Local!");
            // if(bf) bf();
            return;
        }
        self.FBEventStatis("BigButterfly-AdisPlay");
        video_3.showAsync()
        .then(function() {
            // self.preloadAd_getBigButterflyReward();
            // self.m_canShowGetButterflyRewardAd = false;
            cc.find("dialogLayer").getComponent("DialogLayer").show("playAd_getBigButterflyReward Rewarded video preloaded");
            if(bf) bf();
        })
        .catch(function(e){
            const obj = {
                "tag": "BigButterfly-PlayAdisError",
                "msg": "msg::" + e.message,
            };
            query.sendRequest(200, query.sendDebugMsg, obj);
            self.FBEventStatis("BigButterfly-PlayAdisError"+e.message);
            self.FBEventStatis("BigButterfly-PlayAdisError","msg::"+e.message);
            cc.find("dialogLayer").getComponent("DialogLayer").show("playAd_getBigButterflyReward:" + e.message);
        });
    };
    //统计信息
    this.FBEventStatis = function(parm,str="null"){
        // console.log("parm",parm);
        if (typeof FBInstant === 'undefined') return;
        if(window.Global.statis){
            if(str!=="null") {
                const obj = {
                    "tag": "BigButterfly-PlayAdisError",
                    "msg": "msg::" + str,
                };
                query.sendRequest(200, query.sendDebugMsg, obj);
            }
            FBInstant.logEvent(parm);
        }
    };
    //获取推送的信息
    this.getPushInfo = function(){
        var self = this;
        if (typeof FBInstant === 'undefined') return 0;
        var pushData  = FBInstant.getEntryPointData();
        if(pushData){
            var count =  (pushData/ 10000).toFixed(0);
            return count;
        }
        return 0;
    };
    //检测能否发送到桌面
    this.checkIsSendToDesktop = function(){
        var isShow = false;
        if (typeof FBInstant === 'undefined') return isShow;
        FBInstant.canCreateShortcutAsync()
        .then(function(canCreateShortcut) {
            if (canCreateShortcut) {
                isShow = canCreateShortcut;
            }
            return isShow;
        });
    };
    //发送到桌面
    this.sendShortcutToDesktop = function(){
        FBInstant.canCreateShortcutAsync()
        .then(function(canCreateShortcut) {
            console.log("canCreateShortcut",canCreateShortcut)
            if (canCreateShortcut) {
                FBInstant.createShortcutAsync()
                    .then(function() {
                    // Shortcut created
                    LogUtils.log("发送桌面成功  应该给奖励")
                    })
                    .catch(function() {
                    // Shortcut not created
                    LogUtils.log("发送桌面失败")
                    });
            }else{

            }
        });
    };
    /**
    * ---------------------------------从facebook获取 或保存数据
    */
    //获取数据
    this.getUserData = function(bf1,bf2,bf3){
        if (typeof FBInstant === 'undefined') return;
        FBInstant.player
        .getDataAsync(['obj'])
        .then(function(data) {
            console.log('data is loaded',data);
            var obj = data['obj'];
            if(obj){
                if(bf1)bf1(obj);
            }else{
                console.log("没有数据")
               if(bf2)bf2();
            }
        });
    };
    //保存数据
    this.uploadData = function(obj){
        // console.log("obj",obj);
        if (typeof FBInstant === 'undefined') return;
        if(obj){
            FBInstant.player
            .setDataAsync({
                obj: obj,
            })
            .then(function() {
            console.log('data is set',obj);
            });
        }
    }
}
var _instance = null;
module.exports = function(){
    if(!_instance){
        _instance = new FaceBookUtils();
    }
    return _instance;
};
